//
//  HSMessageController.swift
//  HomeSchoolDemo
//
//  Created by Mac on 16/9/26.
//  Copyright © 2016年 chendong. All rights reserved.
//

import UIKit

/*
 表格视图的性能优化，（性能调优）
 1.所有的图片不要使用原生的裁剪圆角模式()
 2.尽量不要使用透明设置
 3.所有参数提前准备好，在需要的时候直接获取使用
 4.包括视图尽量不要使用延时加载,都提前准备好
 */


class HSMessageController: HSBasicController {
    //数据源数组
    let messageListVM = HSMessageslistViewModel()
    //输入工具栏
    var inputToolBarV:UIView!
    //文本输入框
    var inputTextF:UITextField!
    //记录键盘状态
    var isKeyboardshow = false
    //记录当前点击按钮记录的cell
    var currentCell = HSMessageCell()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //注册原形cell
        
        tableView.register(UINib(nibName: "HSMessageCell", bundle: nil) , forCellReuseIdentifier: "MessageCell")
        //tableView.register(UITableViewCell.self, forCellReuseIdentifier: "MessageCell")
        tableView.estimatedRowHeight = 200
        tableView.rowHeight = UITableViewAutomaticDimension
        //添加右边消息按钮
        let rightBtn = UIBarButtonItem(imageName: "release_msg_nor", bgImageName: "release_msg_press", target: self, action: #selector(rightBtnClicked))
        navigationItem.rightBarButtonItem = rightBtn
        //添加刷新控件
        loadData()
        //添加输入工具条
        inputTextView()
        //注册监听键盘弹出的通知
        NotificationCenter.default.addObserver(self, selector: #selector(notificationWithKeyboard(notify:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
    //右边按钮的监听回调
    @objc fileprivate func rightBtnClicked(){
        let releseVc = HSReleaseInfoController()
        releseVc.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(releseVc, animated: true)
    }
    
    override func loadData() {
        //请求数据
        refrshC.beginRefreshing()
        //获得刷新类型
        let loType = isPull ? loadType.pull : loadType.drop
        messageListVM.requestMessage(loadType: loType) {[weak self] (err, isRefresh) in
            //关闭刷新控件
            self?.refrshC.endRefreshing()
            //记录刷新状态
            self?.isPull = false
            //判断是否刷新视图
            if err != nil{
                return
            }
            if isRefresh {
                //刷新视图
                self?.tableView.reloadData()
            }
        }
    }
    
}
// MARK: - Table view data source
extension HSMessageController{
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return messageListVM.messages.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MessageCell", for: indexPath) as! HSMessageCell
        //设置选中模式
        cell.selectionStyle = .none
        //获得对应的视图模型
        let messageVM = messageListVM.messages[indexPath.row]
        cell.messageVM = messageVM
        cell.likeBtnCallback = {(clickCell) -> () in
            //print("点赞",clickCell)
        }
        
        cell.replayBtnCallback = {[weak self] (clickCell) -> () in
            //记录当前cell
            self?.currentCell = cell
            //设置输入框为第一响应者，出发键盘自动弹出
            self?.replayBtnClicked(cell: clickCell as! HSMessageCell)
        }
        
        return cell
    }
}

//MARK - 点赞回复相关功能
extension HSMessageController{
    ///输入框视图
    func inputTextView() {
        //背景视图
        inputToolBarV = UIView(frame: CGRect(x: 0, y: screenH, width: screenW, height: 44))
        inputToolBarV.backgroundColor = UIColor().colorWithHex(0xf0f0f0)
        
        //添加一个输入框
        inputTextF = UITextField(frame: CGRect(x: 8, y: 0, width: screenW - 66, height: 44))
        inputTextF.placeholder = "评论就是一种鼓励"
        inputTextF.borderStyle = .roundedRect
        inputTextF.clearButtonMode = .always
        inputTextF.font = UIFont.systemFont(ofSize: 15)
        inputTextF.textColor = UIColor.black
        inputToolBarV.addSubview(inputTextF)
        
        //添加一个确定按钮
        let suerBtn = UIButton(frame: CGRect(x: screenW - 58, y: 0, width: 50, height: 44))
        suerBtn.setTitle("确定", for: .normal)
        suerBtn.setTitleColor(#colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1), for: .normal)
        suerBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        inputToolBarV.addSubview(suerBtn)
        //添加按钮的监听回调方法
        suerBtn.addTarget(self, action: <#T##Selector#>, for: <#T##UIControlEvents#>)
        
        let kWindow = UIApplication.shared.keyWindow
        kWindow?.addSubview(inputToolBarV)
    }
    
    //MARK: -确定按钮的监听回调方法
    fileprivate func sureBtnClicked(){
        //退出键盘
        inputTextF.resignFirstResponder()
        //获取输入内容
        let inputText = inputTextF.text
        guard inputText != "" else {
            HSAlertView.bottomAlertView("输入内容不能为空")
            return
        }
        //获得接口
        let url = "ZH-schoolname-S-submitJXReplay"
        //获得参数
        //用户key
        let key = userInfo["key"] ?? 0
        //通知ID
        let messageVM = currentCell.messageVM
        let not_id = messageVM?.message.not_id ?? 0
        //设置参数字典
        let param = ["key":key,"id":not_id,"content":inputText,"user_type":2]
        
        HSNetworkTools.shared.downloadData(url: url, parameters: param) { (data, err) in
            print(data,err)
        }
        
        
        
    }
    
    ///回复按钮的点击回调
    func replayBtnClicked(cell:HSMessageCell) {
        //用于记录点击的是否为同一个cell
        let cellEqual = currentCell == cell
        //记录当前cell
        currentCell = cell
        //设置输入框为第一响应者，触发键盘自动弹出
        if inputTextF.isFirstResponder{
            if cellEqual {
            inputTextF.resignFirstResponder()
            }
        }else{
            inputTextF.becomeFirstResponder()
        }
        
        if !cellEqual {
            inputTextF.becomeFirstResponder()
        }
        
    }
    
    func notificationWithKeyboard(notify:Notification){
        print(notify.userInfo)
        //获得键盘的Y值
        let keyboardRect = notify.userInfo?["UIKeyboardFrameEndUserInfoKey"] as? NSValue
        let keyboardY = keyboardRect?.cgRectValue.minY ?? 0
        print(keyboardY)
        //取反
        isKeyboardshow = !(keyboardY >= screenH)
        //计算工具栏的Y值
        let toolBarY = isKeyboardshow ? (keyboardY - 44) : (keyboardY + 44)
        inputToolBarV.frame.origin.y = toolBarY
        
        //适配表格视图高度跟随键盘高度
        //获得当前窗口的视图
        let kWindow = UIApplication.shared.keyWindow
        //获得cell参照于窗口的frame
        let cellFrame = kWindow?.convert(currentCell.frame, from: tableView)
        //获得cell的底部Y值
        let cellMaxY = cellFrame?.maxY ?? 0
        //计算表格视图的偏移量
        let offSetY = cellMaxY - toolBarY
        if offSetY > 0 {
            //获得表格视图当前的便宜量
            let currentOffset = tableView.contentOffset.y
            //重新设置
            tableView.setContentOffset(CGPoint(x: 0, y: offSetY + currentOffset), animated: true)
        }
        
    }
    
    //滚动退出编辑事件
    override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        inputTextF.resignFirstResponder()
    }
    
}
























